package com.ruoyi.user.model.factory.impl;


import com.ruoyi.common.core.enums.CacheKey;
import com.ruoyi.common.core.pojo.entity.UserInfo;
import com.ruoyi.common.core.pojo.vo.TokenVO;
import com.ruoyi.common.redis.cache.CacheTemplate;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.user.model.enums.LoginStrategy;
import com.ruoyi.user.model.factory.LoginFactory;
import com.ruoyi.user.model.pojo.entity.User;
import com.ruoyi.user.model.pojo.request.app.LoginRequest;
import com.ruoyi.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class LoginFactoryCodeImpl implements LoginFactory {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private TokenService tokenService;

    @Override
    public TokenVO<String> login(LoginRequest loginRequest) throws Exception {
        iUserService.verifyCode(loginRequest.getPhone(), loginRequest.getSecretKey());
        User one = iUserService.loginVerify(loginRequest.getPhone());
        User cacheUser = CacheTemplate.getCache(CacheKey.USER_INFO.getKey(String.valueOf(one.getId())), User.class, () -> {
            CacheTemplate.setCache(CacheKey.USER_INFO.getKey(String.valueOf(one.getId())), one);
            return one;
        });

        Map<String, Object> appToken = tokenService.createAppToken(one.getId(), one.getNickName(),one.getStatus());
        String authorization = (String) appToken.get("access_token");
        return TokenVO.<String>builder()
                .nickname(cacheUser.getNickName())
                .id(String.valueOf(cacheUser.getId()))
                .authorization(authorization)
                .other(cacheUser.getPhone())
                .avatarUrl(cacheUser.getPhoto())
                .loginEnum(loginRequest.getLoginEnum())
                .rongYunToken(cacheUser.getRongToken())
                .isAuthentication(one.getIsAuth())
                .build();
    }

    @Override
    public LoginStrategy getStrategy() {
        return LoginStrategy.CODE;
    }
}
